package com.ws.gold.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ws.gold.domain.AiAnalysis;
import com.ws.gold.domain.RealtimeGoldPrice;
import com.ws.gold.domain.WarehouseHoldSituation;
import com.ws.gold.mapper.AiAnalysisMapper;
import com.ws.gold.service.AiAnalysisService;
import com.ws.gold.service.RealtimeGoldPriceService;
import com.ws.gold.service.WarehouseHoldSituationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ws
 * @create 2025/6/29
 */
@Slf4j
@Service
@AllArgsConstructor
public class AiAnalysisServiceImpl extends ServiceImpl<AiAnalysisMapper, AiAnalysis> implements AiAnalysisService {

    private final RealtimeGoldPriceService realtimeGoldPriceService;

    private final WarehouseHoldSituationService warehouseHoldSituationService;

    public String getAiData(){
        String userId = "338797827";
        try {
            String url = "https://spark-api-open.xf-yun.com/v2/chat/completions";

            // 创建最外层的JSON对象
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("user", userId);
            jsonObject.put("model", "x1");
            // 创建messages数组
            JSONArray messagesArray = new JSONArray();
            // 创建单个消息的JSON对象
            JSONObject messageObject = new JSONObject();
            //设置问题
            //获取最近三天的数据
            List<RealtimeGoldPrice> list = realtimeGoldPriceService.lambdaQuery().between(RealtimeGoldPrice::getCreateTime, LocalDateTimeUtil.offset(LocalDateTime.now(), -12, ChronoUnit.HOURS), LocalDateTime.now()).orderByAsc(RealtimeGoldPrice::getCreateTime).list();
            com.alibaba.fastjson2.JSONObject object = com.alibaba.fastjson2.JSONObject.of("xLabels", list.stream().map(item -> LocalDateTimeUtil.formatNormal(item.getCreateTime())).collect(Collectors.toList()), "yValues", list.stream().map(RealtimeGoldPrice::getPrice).collect(Collectors.toList()));
            String temp = "根据我提供的12小时内实时金价折线图的x轴和y轴数据: {data},以及我的平均买入价格: {price},给出追仓位置和止盈止损位置,按照类似下面这样的格式返回给我:\n" +
                    "建议追仓位置:xxx~xxx,xxx~xxx;建议止盈位置:xxx+;建议止损位置:xxx-";
            String replace = temp.replace("{data}", JSON.toJSONString(object));
            WarehouseHoldSituation warehouseHoldSituation = warehouseHoldSituationService.lambdaQuery().list().stream().findFirst().orElse(null);
            Double buyRealPrice = 768.0;
            if(ObjUtil.isNotEmpty(warehouseHoldSituation)){
                buyRealPrice = warehouseHoldSituation.getBuyRealPrice();
            }
            String question = replace.replace("{price}", buyRealPrice.toString());
            log.info("问题: {}", question);
            messageObject.put("role", "user");
            messageObject.put("content", question);
            messageObject.put("temperature", "0.5");
            // 将单个消息对象添加到messages数组中
            messagesArray.put(messageObject);
            // 将messages数组添加到最外层的JSON对象中
            jsonObject.put("messages", messagesArray);
            // 设置stream属性为true
            jsonObject.put("stream", true);
            jsonObject.put("max_tokens", 4096);
            // System.err.println(jsonObject);

            String header = "Authorization: Bearer" + ""; // 注意此处替换自己的key和secret

            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Authorization", header);
            con.setDoOutput(true);

            OutputStream os = con.getOutputStream();
            os.write(jsonObject.toString().getBytes());
            os.flush();
            os.close();

            int responseCode = con.getResponseCode();
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();


            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
//                System.out.println(inputLine);
            }
            in.close();
            //  System.err.println(userId + " 的文章生成任务内容如下：\n" + response);
            // 流式返回结果打印
            String jsonStr = response.substring(5);
            if (!jsonStr.isEmpty()) {
                log.info("回复: {}", jsonStr);
            }
            com.alibaba.fastjson2.JSONArray objects = com.alibaba.fastjson2.JSONArray.of(jsonStr.split("data:"));
            objects.remove(objects.size()-1);
            String jsonString = JSON.toJSONString(objects);
            List<com.alibaba.fastjson2.JSONObject> jsonObjects = com.alibaba.fastjson2.JSONArray.parseArray(jsonString, com.alibaba.fastjson2.JSONObject.class);
            List<Object> collect = jsonObjects.stream().flatMap(item -> item.getJSONArray("choices").stream()).collect(Collectors.toList());
            return collect.stream().map(item -> ((com.alibaba.fastjson2.JSONObject) item).getJSONObject("delta").getString("reasoning_content")).collect(Collectors.joining()).replace("null", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
